package com.bocloud.mq;


import com.bocloud.model.Login;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;


/**
 * rabbitmq发送消息类
 */
@Component
public class SendMessage implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {

    Logger log = LoggerFactory.getLogger(SendMessage.class);
    @Autowired
    AmqpTemplate amqpTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }


    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            System.out.println("消息发送成功:" + correlationData);
        } else {
            System.out.println("消息发送失败:" + cause);
        }

    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        System.out.println(message.getMessageProperties().getCorrelationId() + " 发送失败");

    }

    public void send(Login login) {
        try {
            amqpTemplate.convertAndSend("directExchange", "login", login);
            log.info("direct");
        } catch (Exception e) {
            log.error("消息发送失败");
        }

    }

    /*发送send1，topicExchange只会接受到一个消息，routingKey匹配为login.#*/
    public void send1(Login login) {
        try {
            amqpTemplate.convertAndSend("topicExchange", "login.news", login);
            log.info("topic1");
        } catch (Exception e) {
            log.error("消息发送失败");
        }

    }

    /*发送send2，topicExchange会接受到两个消息，routingKey匹配为login.new和login.#*/
    public void send2(Login login) {
        try {
            amqpTemplate.convertAndSend("topicExchange", "login.new", login);
            log.info("topic2");
        } catch (Exception e) {
            log.error("消息发送失败");
        }
    }

    /*发送send3，不管routingKey是什么，都会被忽略，消息会发到和fanoutExchang绑定的队列上*/
    public void send3(Login login) {
        try {
            amqpTemplate.convertAndSend("fanoutExchange", "kfc", login);
            log.info("fanout1");
        } catch (Exception e) {
            log.error("消息发送失败");
        }

    }


}
